package cn.xinfei.xdecision.common.dynamic;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Aspect
@Component
public class DynamicDataSourceAop {

    @Value("${spring.application.name}")
    private String serviceName;


    @Before("@annotation(cn.xinfei.xdecision.common.dynamic.DynamicDataSourceSwitch)")
    public void setDataSource() {
        DataSourceType type = DataSourceType.get(serviceName);
//        log.debug("switch datasource type={}", type);
        DynamicDatasourceContextHolder.setDataSourceType(type);
    }


    @After("@annotation(cn.xinfei.xdecision.common.dynamic.DynamicDataSourceSwitch)")
    public void clearDataSourceType() {
        DataSourceType type = DataSourceType.get(serviceName);
//        log.debug("clear datasource type={}", type);
        DynamicDatasourceContextHolder.clearDataSourceType();
    }
}
